require 'treenode.rb'
require 'treeservice.rb'

class TreeApplication
    def initialize
        @myTree = TreeNode.new('root')
        @searchResults = ''
    end	

    def	buildTreeFromFile(filename)
        file = File.open(filename)
        file.read.split(/\n/).each do |line|
            buildTreeFromString(line.strip) 
        end
    end
    
    def buildTreeFromString(line)
        node = @myTree
        
        nodeValues = line.split("|")
        
        if line.count(',') != 0 #If string has relationships delimited by commas
            node = buildTreeFromArray(buildArrayFromStringWithRelationships(nodeValues), node)
        else
            nodeValues.each do |nodeValue|
                node = node.addChild(TreeNode.new(nodeValue))
            end
        end
    end
    
    def buildTreeFromArray(treeArray, rootNode)
        lastNodes = []
        treeArray.reverse_each do |nodeArray|
            
            returnedNodes = []
            nodeArray.each_with_index do |nodeValue, nodeIndex|
                if lastNodes.empty? #If first run, prime the lastNodes
                    lastNodes[nodeIndex] = TreeNode.new(nodeValue)
                else
                    workingNode = TreeNode.new(nodeValue)

                    lastNodes.each { |lastNode|
                        workingNode.addChild(TreeService.instance.cloneNode(lastNode))
                        returnedNodes[nodeIndex] = workingNode
                    }
                end
            end
            
            if !returnedNodes.empty?
                lastNodes = returnedNodes
            end
        end

        #Add resulting tree(s) to the rootNode
        lastNodes.each { |node| rootNode.addChild(node) }
        
        rootNode
    end
    
    def buildArrayFromStringWithRelationships(nodeValues)
        returnValue = [[],[],[],[],[]]
        
        nodeValues.each_with_index { |nodeValue, nodeIndex|
            nodeValue.split(',').each_with_index { |splitNodeValue, splitNodeIndex| 
                returnValue[nodeIndex][splitNodeIndex] = splitNodeValue
            }
        }

        returnValue
    end
    
    def search(value)
        @searchResults = TreeService.instance.search(@myTree, value)
    end
    
    def printGraph()
        @searchResults.each do |node| 
            print "\n" + TreeService.instance.printGraph(node, '|').sub('|root|', '') + "\n" 
        end
    end
end

#Initialize app
myTreeApp = TreeApplication.new()
myTreeApp.buildTreeFromFile($*[0])
myTreeApp.search($*[1])
myTreeApp.printGraph()